/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package models.spider.deprecated.rdf;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.stream.StreamFilter;
import javax.xml.stream.XMLStreamReader;

import org.apache.commons.lang3.StringUtils;

public class UriAdapter extends XmlAdapter<String, String> implements StreamFilter {

    protected String base = "";

    public UriAdapter() {
    }

    public UriAdapter(final String base) {
        this.base = base;
    }

    @Override
    public String unmarshal(final String text) throws Exception {
        return base + text;
    }

    @Override
    public String marshal(final String uri) throws Exception {
        if ("".equals(base)) {
            return uri.toString();
        } else {
            return uri.replaceFirst(base, "");
        }
    }

    @Override
    public boolean accept(final XMLStreamReader reader) {

        if (reader.isStartElement()) {
            String newBase = reader.getAttributeValue("http://www.w3.org/XML/1998/namespace", "base");
            if (null != newBase) {
                newBase = StringUtils.removeEnd(newBase, "/");
                newBase = newBase + "/";
                base = newBase;
            }
        }
        return true;
    }
}